<template>
  <div>
    <el-table
      ref="refActTable"
      v-loading="listLoading"
      :data="list"
      :height="400"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table_expand">
            <el-form-item label="活动类型">
              <span v-if="props.row.scheme === 3" class="icon_color_4">生日</span>
              <span v-if="props.row.scheme === 2" class="icon_color_1">客情</span>
              <span v-if="props.row.scheme === 1" class="icon_color_2">沙龙</span>
              <span v-if="props.row.scheme === -1" class="icon_color_3">其他</span>
            </el-form-item>
            <el-form-item label="活动时间">
              <span>{{ props.row.start }}</span>
              <span v-if="props.row.end" style="margin: 0px 5px 0px 5px">到</span>
              <span v-if="props.row.end">{{ props.row.end }}</span>
            </el-form-item>
            <el-form-item label="活动负责人">
              <span>{{ props.row.kname }}</span>
            </el-form-item>
            <el-form-item label="邀请人数">
              <span>{{ props.row.clerkCount }}</span>
            </el-form-item>
            <el-form-item label="活动方案">
              <span>{{ props.row.plan }}</span>
            </el-form-item>
            <el-form-item label="活动评分">
              <div v-if="ops.isScore && actScoreId === props.row.id">
                <el-input-number
                  v-model="props.row.score"
                  :precision="2"
                  :step="1.0"
                  :max="100"
                  :min="0"
                  style="margin: 0px 5px 0px 0px"
                  size="small"></el-input-number>
                <el-button v-if="ops.isScoreUpdating" size="mini" type="primary" plain disabled icon="el-icon-loading">
                  修改评分
                </el-button>
                <el-button v-else size="mini" type="primary" plain @click.stop="goActScoreUpdate(props.row)">
                  修改评分
                </el-button>
              </div>
              <div v-else>
                <span v-if="props.row.score === null || props.row.score === undefined">尚未评分</span>
                <span v-else>{{ props.row.score }}</span>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center" width="100">
        <template slot-scope="{ row }">
          <div v-if="row.scheme === 3" class="icon_color_4">生日</div>
          <div v-if="row.scheme === 2" class="icon_color_1">客情</div>
          <div v-if="row.scheme === 1" class="icon_color_2">沙龙</div>
          <div v-if="row.scheme === -1" class="icon_color_3">其他</div>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" width="120">
        <template slot-scope="{ row }">{{ row.start | actDateFileter }}</template>
      </el-table-column>
      <el-table-column prop="kname" label="活动负责人" align="center" width="120"></el-table-column>
      <el-table-column label="活动状态" align="center" width="100">
        <template slot-scope="{ row }">{{ row | actStateFileter }}</template>
      </el-table-column>
      <el-table-column prop="clerkCount" label="邀请人数" align="center" width="100"></el-table-column>
      <el-table-column prop="plan" label="活动简介" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button v-if="!isActComplete(row)" type="primary" size="mini" plain @click.stop="goActClerkFilter(row)">
            修改
          </el-button>
          <el-button
            v-else-if="row.score === undefined || row.score === null"
            type="success"
            size="mini"
            plain
            @click.stop="goActScore(row)">
            评分
          </el-button>
          <el-button v-else type="success" size="mini" plain disabled>{{ row.score }}分</el-button>
          <el-button v-if="ops.isDeleting" type="danger" size="mini" plain disabled icon="el-icon-loading">
            删除
          </el-button>
          <el-button v-else type="danger" size="mini" plain @click.stop="goActDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"></pagination>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
import * as actApi from '@/api/activity';
import Pagination from '@/components/Pagination';
import '@/utils/datefmt';
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';

/**
 * @param {Object} val
 * @return {void}
 */
function getActState(val) {
  if (!val) {
    return '';
  }
  if (!val.start) {
    return '';
  }
  if (val.score !== undefined && val.score > 0) {
    return '已结束';
  }
  const now = new Date();
  const tmr = new Date();
  tmr.setDate(tmr.getDate() + 1);
  tmr.setHours(0, 0, 0, 0);
  const act = new Date(val.start);
  if (val.scheme === 3 /* 生日, 有效期一个月 */) {
    if (now.getFullYear() == act.getFullYear() && now.getMonth() == act.getMonth()) {
      return '已开始';
    }
    if (
      now.getFullYear() > act.getFullYear() ||
      (now.getFullYear() == act.getFullYear() && now.getMonth() > act.getMonth())
    ) {
      return '已结束';
    }
    return '未开始';
  }
  if (!val.end) {
    if (act.getTime() > now.getTime()) {
      return '未开始';
    }
    if (act.getTime() < tmr.getTime()) {
      return '已结束';
    }
    return '已开始';
  } else {
    const end = new Date(val.end);
    if (act.getTime() > now.getTime()) {
      return '未开始';
    } else if (end.getTime() <= now.getTime()) {
      return '已结束';
    }
    return '已开始';
  }
}

export default {
  name: 'ActivityList',
  components: {
    Pagination,
  },
  filters: {
    actDateFileter(val) {
      if (!val) {
        return '';
      }
      const d = new Date(val);
      return d.format('yyyy/MM/dd');
    },
    actStateFileter(val) {
      return getActState(val);
    },
  },
  data() {
    return {
      list: [], // 页面 table 数据
      listLoading: false, // 页面数据加载中?
      total: 0,
      listQuery: { page: 1, limit: 10 },
      ops: { isDeleting: false, isScore: false, isScoreUpdating: false },
      actScoreId: 0, // 当前评分的活动id, 用于控制是否显示评分输入框
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
  },
  mounted() {
    // this.getList(undefined);
  },
  methods: {
    handleSelectionChange(val) {},
    isActComplete(row) {
      const sts = getActState(row);
      return '已结束' === sts;
    },
    goActReview(id) {},
    goActDel: async function (row) {
      this.ops.isDeleting = true;
      await actApi
        .delActivity(row.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            MessageBox.alert('删除失败');
            return;
          }
          this.getList();
        })
        .finally(() => {
          this.ops.isDeleting = false;
        });
    },
    goActClerkFilter(row) {
      if (this.isActComplete(row)) {
        MessageBox.alert('已结束的活动不能修改');
        return;
      }
      this.$emit('act-modify', row);
    },
    goActScore(row) {
      if (!this.$refs.refActTable) {
        return;
      }
      this.ops.isScore = true;
      this.actScoreId = row.id;
      this.$refs.refActTable.toggleRowExpansion(row, true);
    },
    goActScoreUpdate: async function (row) {
      this.ops.isScoreUpdating = true;
      await actApi
        .activityUpdate(row)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            MessageBox.alert('评分修改失败');
            return;
          }
          MessageBox.alert('评分修改成功');
          this.ops.isScore = false;
          this.$refs.refActTable.toggleRowExpansion(row, false);
        })
        .catch(err => {
          console.log(err);
          MessageBox.alert('评分修改失败');
        })
        .finally(() => {
          this.ops.isScoreUpdating = false;
        });
    },
    getList: async function (kname, pageNumber, pageSize) {
      if (!this.openId) {
        // 不属于任何门店的用户(通常是系统管理员)
        return;
      }
      this.listLoading = true;
      let page = this.listQuery.page;
      let size = this.listQuery.limit;
      if (pageNumber && pageSize) {
        page = pageNumber;
        size = pageSize;
      }
      await actApi
        .getActivityPage(page, size, this.openId, !!kname ? kname : null)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            MessageBox.alert('查询活动列表失败');
            return;
          }
          this.list.splice(0, this.list.length);
          this.list.push(...res.data.data.records);
          this.total = res.data.data.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
$mid_title_color_overtime: #ff5b5b;
$mid_title_color_complete: #724eff;
$mid_title_color_not_participated: #f29339;
$mid_title_birthday: #469b78;

.icon_color_1 {
  color: $mid_title_color_not_participated;
}

.icon_color_2 {
  color: $mid_title_color_complete;
}

.icon_color_3 {
  color: $mid_title_color_overtime;
}

.icon_color_4 {
  color: $mid_title_birthday;
}

.table_expand {
  font-size: 0;
}
.table_expand label {
  width: 90px;
  color: #99a9bf;
}
.table_expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
